<template>
  <div class="main-wrapper">
    <el-tabs tab-position="left" @tab-change="handleTabChange" class="hd-left-tabs demo-tabs">
      <el-tab-pane label="资料设计">
        <div class="basic-box-wrapper">
          <div class="left-box">
            <el-scrollbar class="left-box-scroll-wrapper">
              <!-- <p v-for="item in 40" :key="item" class="scrollbar-demo-item">{{ item }}</p> -->
              <el-form
                ref="dealerFormRef"
                :rules="rules"
                :disabled="dialogData.isView"
                :model="dialogData.itemInfo"
                label-width="160px"
                label-suffix=" :"
                :hide-required-asterisk="dialogData.isView"
              >
                <el-row>
                  <el-col :span="16">
                    <el-row>
                      <div class="opt-title-box">
                        <div class="info-title">企业基本信息</div>
                      </div>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司名称" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.name"
                          placeholder="请填写名称"
                          maxlength="100"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司简称" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.sname"
                          placeholder="请填写简称"
                          maxlength="100"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="所属区域" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.relationPCA"
                          placeholder="请填写简称"
                          maxlength="100"
                          show-word-limit
                          disabled
                        ></el-input>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="邀请码" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.inviteCode"
                          placeholder="邀请码"
                          disabled
                          maxlength="100"
                          show-word-limit
                        >
                          <template #append>
                            <el-button :icon="Refresh" @click="handleRefreshCode" />
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <div class="opt-title-box">
                        <div class="info-title">更多信息</div>
                      </div>
                    </el-row>
                    <el-row>
                      <el-form-item label="所属行业" class="form-item">
                        <el-select v-model="dialogData.itemInfo.industry" placeholder="请选择所属行业" style="width: 100%">
                          <el-option
                            v-for="item in dialogData.companyIndustrys"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司规模" class="form-item">
                        <el-select v-model="dialogData.itemInfo.cpysize" placeholder="请选择公司规模" style="width: 100%">
                          <el-option
                            v-for="item in dialogData.companySizes"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司性质" class="form-item">
                        <el-select v-model="dialogData.itemInfo.nature" placeholder="请选择公司性质" style="width: 100%">
                          <el-option
                            v-for="item in dialogData.companyNatures"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司地址" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.address"
                          placeholder="请填写手机号码"
                          maxlength="100"
                          show-word-limit
                        ></el-input>
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="成立日期" class="form-item">
                        <el-date-picker v-model="dialogData.itemInfo.companyDate" type="date" placeholder="请选择" />
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-form-item label="公司简介" class="form-item">
                        <el-input
                          v-model="dialogData.itemInfo.summary"
                          placeholder="请选择公司介绍"
                          type="textarea"
                          rows="6"
                          maxlength="1000"
                          show-word-limit
                        />
                      </el-form-item>
                    </el-row>
                  </el-col>
                  <el-col :span="8">
                    <div class="upload-box">
                      <UploadImg
                        v-model:imageUrl="dialogData.itemInfo.companyImage"
                        :disabled="dialogData.isView"
                        :file-size="10"
                        width="220px"
                        height="220px"
                      >
                        <template #tip>营业执照不能超过 10M </template>
                      </UploadImg>
                    </div>
                  </el-col>
                </el-row>
              </el-form>
            </el-scrollbar>
          </div>
          <div class="right-box">
            <div class="opt">
              <el-button type="primary" size="small" :icon="CirclePlus" @click="handleSubmit">保存信息</el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="员工管理">
        <ProTable ref="pTable" :columns="columns" :request-api="getTableList">
          <template #tableHeader>
            <el-button type="primary" :icon="CirclePlus" @click="handleOpenDialog(OptEnum.CREATE, {}, dialogData.itemInfo.id)">
              添加用户
            </el-button>
          </template>
          <template #userName="scope">
            <div class="apply-user-box">
              <div class="item-image">
                <img :src="getAvatorUrl(scope.row.userAvator)" alt="用户头像" />
              </div>
              <div class="item-user">{{ scope.row.userName }}</div>
            </div>
          </template>
          <template #status="scope">
            <el-tag :type="scope.row.status === 6 ? 'danger' : 'primary'">
              {{ filterEnum(scope.row.status, sysStatusType) }}
            </el-tag>
          </template>
          <template #flexScore="scope">
            <el-rate v-model="scope.row.flexScore" disabled text-color="#ff9900" />
          </template>
          <template #operation="scope">
            <!-- <el-button type="primary" text @click="handleOpenDialog(OptEnum.VIEW, scope.row)">修改</el-button> -->
            <el-button type="danger" :icon="Delete" size="small" text @click="handleDeleteRowItem(scope.row)"> 删除 </el-button>
          </template>
        </ProTable>
      </el-tab-pane>
      <el-tab-pane label="系统通知">系统消息</el-tab-pane>
    </el-tabs>
    <DealerUserDialog ref="dialogRef" @refresh-list="handleRefreshList" />
  </div>
</template>

<script setup lang="ts">
import { OptEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { DealerInfoEntity } from "@/biz/interface/modules/DealerType";
import { onMounted, reactive, ref } from "vue";
import { CirclePlus, Refresh, Delete } from "@element-plus/icons-vue";
import { ElMessage, FormInstance, TabPaneName } from "element-plus";
import UploadImg from "@/components/Upload/Img.vue";
import {
  getCompanySysDataApi,
  getDealerInfoApi,
  getDealerInviteCodeApi,
  getDealerUsersVoListApi,
  deleteDealerUserApi
} from "@/api/modules/dealer/basic";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import defaultAvatar from "@/assets/images/davator.png";
import { filterEnum } from "@/utils";
import { sysStatusType } from "@/biz/datas/sysData";
import { useHandleData } from "@/hooks/useHandleData";
import DealerUserDialog from "./components/DealerUserDialog.vue";

// const options = ref([] as any);

// //提交按钮，避免多次提交
const btnLoading = ref(false);

//页面的数据
interface DealerDialogOption extends DialogParam {
  optType: OptEnum;
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  //当前的数据对象
  itemInfo: DealerInfoEntity;
  //其它的数据都继续在这里加
  companyNatures: { label: string; value: number }[];
  companyIndustrys: { label: string; value: number }[];
  companySizes: { label: string; value: number }[];
}

const dialogData = reactive<DealerDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  itemInfo: {
    name: ""
  },
  companyNatures: [],
  companyIndustrys: [],
  companySizes: []
});

//数据较验
const rules = reactive({});

// 生成经销商邀请码
const handleRefreshCode = () => {
  // console.log("开始重新生成邀请码");
  getDealerInviteCodeApi().then(res => {
    // console.log(res);
    dialogData.itemInfo.inviteCode = (res?.data as unknown as string) || "";
  });
};

const initItemInfo = () => {
  dialogData.itemInfo = {
    name: ""
  };
};

const getItemInfo = async () => {
  let { data } = await getDealerInfoApi({});
  if (data) {
    dialogData.itemInfo = data as unknown as DealerInfoEntity;
  } else {
    initItemInfo();
  }
};

const pTable = ref();

const getAvatorUrl = (aurl: string) => {
  let url = defaultAvatar;
  if (aurl) {
    url = aurl;
  }
  return url;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  console.log("请求参数", newParams);
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    // delete newParams.createTime;
    return getDealerUsersVoListApi({ ...newParams, dealerId: dialogData.itemInfo.id });
  } else {
    return [];
  }
};
// 表格列配置
const columns: Partial<ColumnProps>[] = [
  { type: "selection", width: 80, fixed: "left" },
  {
    prop: "userName",
    label: "用户",
    search: { el: "input" }
  },
  {
    prop: "status",
    label: "状态"
  },
  {
    prop: "createDate",
    label: "创建时间"
  },
  {
    prop: "flexScore",
    label: "评分"
  },
  {
    prop: "operation",
    width: 220,
    fixed: "right",
    label: "操作"
  }
];

//刷新数据列表
const handleRefreshList = () => {
  pTable.value.getTableList();
};

// 删除信息
const handleDeleteRowItem = async (params: any) => {
  // console.log("删除类型");
  await useHandleData(deleteDealerUserApi, { id: params.id! }, `删除【${params.name}】招工类型`);
  handleRefreshList();
};

// tab 切换事情
const handleTabChange = (name: TabPaneName) => {
  console.log(name);
  if (name == 0) {
    // 加载日志流水
    // getJobProcesses();
  } else if (name == 1) {
    // 加载用户
    handleRefreshList();
  } else if (name == 2) {
    // 加载交易记录 目前这个还没有
  }
};

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref();
const handleOpenDialog = (optType: OptEnum, rowData?: { id?: string }, dealerId?: string) => {
  let params = {
    optType: optType,
    rowData: { ...rowData },
    dealerId
  };
  dialogRef.value.acceptParams(params);
};

// 提交数据（新增/编辑）
const dealerFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  dealerFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      ElMessage.success({ message: `企业信息保存成功！` });
      //刷新列表数据
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

onMounted(() => {
  getCompanySysDataApi().then(res => {
    if (res) {
      let data = res.data;
      // console.log("接收到的数据", data);
      // 解析字典值
      data.forEach(item => {
        if (item.colName == "nature") {
          dialogData.companyNatures.push({ label: item.configValue, value: item.configKey - 0 });
        } else if (item.colName == "industry") {
          dialogData.companyIndustrys.push({ label: item.configValue, value: item.configKey - 0 });
        } else if (item.colName == "cpysize") {
          dialogData.companySizes.push({ label: item.configValue, value: item.configKey - 0 });
        }
      });

      // 在获取详情
      getItemInfo();
    }
  });
});
</script>

<style scoped lang="scss">
.main-wrapper {
  // border: 1px solid red;
  background-color: #fff;
  border-radius: 5px;
  display: flex;
  width: 100%;
  height: 100%;
}

.demo-tabs {
  // border: 1px solid red;
  width: 100%;
}

.basic-box-wrapper {
  border: 1px solid var(--el-color-info-light-7);
  width: 99%;
  height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
  margin: 5px;

  .left-box {
    flex: 1;
    // border: 1px solid red;

    .left-box-scroll-wrapper {
      padding: 5px;
      // border: 1px solid blue;
      height: calc(100vh - 200px);
    }
  }

  .right-box {
    width: 100%;
    height: 40px;
    margin-top: 5px;
    // border: 1px solid green;

    border-top: 1px solid var(--el-color-info-light-7);

    .opt {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.form-item {
  width: 100%;
}

.user-box-wrapper {
  border: 1px solid green;
  width: 100%;
  height: 100%;
}

.apply-user-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .item-image {
    height: 48px;
    width: 48px;
    border-radius: 50%;
    overflow: hidden;

    img {
      height: 48px;
      width: 48px;
    }
  }
  .item-user {
    font-size: 0.65rem;
    font-weight: 300;
    margin: 0;
  }
}
</style>
